package cn.openea.perpartner.meily.web.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.openea.perpartner.common.core.text.Convert;
import cn.openea.perpartner.common.core.web.domain.AjaxResult;
import cn.openea.perpartner.common.core.web.page.TablePage;
import cn.openea.perpartner.meily.web.entity.vo.ToDoVo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.openea.perpartner.meily.web.mapper.TodoMapper;
import cn.openea.perpartner.meily.web.entity.Todo;
import cn.openea.perpartner.meily.web.service.ITodoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 待办表(Todo)表服务实现类
 *
 * @author Weird077
 * @since 2023-06-21 10:14:45
 */
@Service("todoService")
public class TodoServiceImpl extends ServiceImpl<TodoMapper, Todo> implements ITodoService {
    @Value("${bpm.rest.url}")
    private String bpmRestUrl;
    private static final String UUID_REGEX = "^[0-9a-fA-F]{32}$";

    @Override
    public List<Todo> selectToDoList(Todo todo) {
        LambdaQueryWrapper<Todo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Todo::getUserId, todo.getUserId());
        wrapper.eq(Todo::getStatus, "Current");
        wrapper.orderByDesc(Todo::getStartTime);
        return list(wrapper);
    }

    @Override
    public List<Todo> selectDoneList(Todo todo) {
        LambdaQueryWrapper<Todo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Todo::getUserId, todo.getUserId());
        wrapper.eq(Todo::getStatus, "ARC");
        wrapper.orderByAsc(Todo::getEndTime);
        return list(wrapper);
    }

    @Override
    public AjaxResult checkUserTaskIsCurrentByTaskId(Todo todo) {
        AjaxResult result = AjaxResult.error("没有该待办");
        if (isValidUUID(todo.getTaskId())) {
            HashMap<String, Object> params = new HashMap<>();
            params.put("appid", "AppletsPro");
            params.put("wf_num", "R_AppletsPro_B007");
            params.put("userId", todo.getUserId());
            params.put("docUnid", todo.getTaskId());
            JSONObject jsonObject = doBpmRequest(params);
            int code = Convert.toInt(jsonObject.getString("code"));
            if (code == 200) {
                result = AjaxResult.success();
            }
        } else {
            LambdaQueryWrapper<Todo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Todo::getUserId, todo.getUserId());
            wrapper.eq(Todo::getTaskId, todo.getTaskId());
            wrapper.eq(Todo::getStatus, "Current");
            long count = count(wrapper);
            if (count > 0) {
                result = AjaxResult.success();
            }
        }
        return result;
    }

    @Override
    public boolean addToDoData(Todo todo) {
        return save(todo);
    }

    @Override
    public boolean saveOrUpdateToDoDataByNodeName(Todo todo) {
        LambdaQueryWrapper<Todo> wrapper = Wrappers.<Todo>lambdaQuery()
                .eq(Todo::getUserId, todo.getUserId())
                .eq(Todo::getNodeName, todo.getNodeName())
                .eq(Todo::getReqNumber, todo.getReqNumber());
        Todo todoData = getOne(wrapper);
        if (BeanUtil.isNotEmpty(todoData)) {
            todoData.setStatus("Current");
            todoData.setStartTime(todo.getStartTime());
            todoData.setPrvUserId(todo.getPrvUserId());
            return updateById(todoData);
        }
        return save(todo);
    }

    /**
     * 获取待办列表-小程序
     *
     * @param vo
     * @return
     */
    @Override
    public List<Todo> selectList(ToDoVo vo) {

        LambdaQueryWrapper<Todo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Todo::getUserId, vo.getUserId());
        // 待办状态
        if (StrUtil.isNotBlank(vo.getStatus())) {
            wrapper.eq(Todo::getStatus, vo.getStatus());
        } else {
            // 默认获取待办
            wrapper.eq(Todo::getStatus, "Current");
        }

        // 关键字
        if (StrUtil.isNotBlank(vo.getSearchStr())) {
            wrapper.and(wrap -> wrap.like(Todo::getSubject, vo.getSearchStr())
                    .or().like(Todo::getReqNumber, vo.getSearchStr())
                    .or().like(Todo::getNodeName, vo.getSearchStr()));
        }

        wrapper.orderByDesc(Todo::getStartTime);
        return list(wrapper);
    }


    @Override
    public boolean updateToDoToDone(String userId, String reqNumber) {
        LambdaUpdateWrapper<Todo> wrapper = Wrappers.lambdaUpdate();
        wrapper.set(Todo::getStatus, "ARC");
        wrapper.set(Todo::getEndTime, DateUtil.now());
        wrapper.eq(Todo::getReqNumber, reqNumber);
        wrapper.eq(Todo::getUserId, userId);
        wrapper.eq(Todo::getStatus, "Current");
        return update(wrapper);
    }

    private JSONObject doBpmRequest(HashMap<String, Object> params) {
        HttpResponse resp = HttpRequest.post(bpmRestUrl)
                .header("sysid", "SysAdmin")
                .header("syspwd", "pass")
                .header("userId", "admin")
                .form(params)
                .execute();
        return JSON.parseObject(resp.body());
    }

    public static boolean isValidUUID(String uuid) {
        boolean isValid = false;
        if (!Pattern.matches(UUID_REGEX, uuid)) {
            isValid = uuid.length() > 20;
        }
        return isValid;
    }
}

